#!/usr/bin/env python
import pika
import sys

"""订阅模式(根据routing_key来接受数据, key相同的消费者会同时接受到)

1. 申请一个交换机并
    - 指定direct模式
2. 申请临时队列
3. 队列绑定交换机
    - 指定routeing_key: 'info', 'warning', 'error'

"""

credentials = pika.PlainCredentials(username='chf', password='123456')  # mq用户名和密码
connection = pika.BlockingConnection(pika.ConnectionParameters(host='117.72.79.182', port=5672, credentials=credentials))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs', exchange_type='direct')

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue

severities = sys.argv[1:]
if not severities:
    sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

for severity in severities:
    channel.queue_bind(
        exchange='direct_logs', queue=queue_name, routing_key=severity)

print(' [*] Waiting for logs. To exit press CTRL+C')


def callback(ch, method, properties, body):
    print(f" [x] {method.routing_key}:{body}")


channel.basic_consume(
    queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()